package com.sdkj.dspservice.modules.analysis.api;

import com.sdkj.dspservice.common.base.controller.BaseController;
import com.sdkj.dspservice.common.config.ProjectConfig;
import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.common.utils.CollectionsUtils;
import com.sdkj.dspservice.common.utils.ExcelUtils;
import com.sdkj.dspservice.common.utils.RedisUtils;
import com.sdkj.dspservice.common.utils.StringUtils;
import com.sdkj.dspservice.modules.analysis.entity.PageAnalysis;
import com.sdkj.dspservice.modules.analysis.entity.PageParamAnalysis;
import com.sdkj.dspservice.modules.analysis.service.PageAnalysisService;
import com.sdkj.dspservice.modules.sys.entity.Annex;
import com.sdkj.dspservice.modules.sys.service.AnnexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "${project-config.apiUrl}/${project-config.version}/analysis/pageAnalysis")
public class PageAnalysisController extends BaseController {

    @Autowired
    private PageAnalysisService pageAnalysisService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProjectConfig projectConfig;
    @Autowired
    private AnnexService annexService;

    /**
     * 查询所有url
     *
     * @return
     */
    @RequestMapping(value = "allUrl")
    public AntdProResult allUrl() {
        AntdProResult result = new AntdProResult();
        RedisUtils redisUtils = new RedisUtils(redisTemplate);
        Object urlList = redisUtils.getObject(RedisUtils.ANALYSIS_MODULE_AUTO_COMPLETE_URL_LIST);
        result.success(urlList);
        return result;
    }

    /**
     * 获取子链接
     *
     * @return
     */
    @RequestMapping(value = "listChildren")
    public AntdProResult listChildren(@RequestBody PageAnalysis pageAnalysis) {
        AntdProResult result = new AntdProResult();
        List<PageAnalysis> pageAnalysisList = new ArrayList<>();
        // 特殊的url，此类url子链接只显示不带参数和?参数合并两条（如果查询的url为带参，则多显示该条）
        String[] specialUrls = new String[]{"wap.jx.10086.cn/hui/release/goods/8755/index.html"};
        // 去除url的http(s)://和参数
        String searchUrl = pageAnalysis.getUrl().split("\\?")[0];
        if(searchUrl.indexOf("://") != -1){
            searchUrl = searchUrl.split("://")[1];
        }
        // 判断是否属于特殊url
        if(StringUtils.inString(searchUrl, specialUrls)){
            // 属于特殊url

            // 插入查询的url
            PageAnalysis pa = new PageAnalysis();
            pa.setUrl(pageAnalysis.getUrl());
            pa.setStartDate(pageAnalysis.getStartDate());
            pa.setEndDate(pageAnalysis.getEndDate());
            // 查询标题
            PageAnalysis titlePa = pageAnalysisService.getTitle(pa);
            if(titlePa != null){
                pa.setTitle(titlePa.getTitle());
            }
            pageAnalysisList.add(pa);

            // 如果查询的为带参数的，还需要插入一条不带参的
            if(pageAnalysis.getUrl().indexOf("?") != -1){
                PageAnalysis pa3 = new PageAnalysis();
                pa3.setUrl(searchUrl);
                pa3.setStartDate(pageAnalysis.getStartDate());
                pa3.setEndDate(pageAnalysis.getEndDate());
                // 查询标题
                PageAnalysis titlePa3 = pageAnalysisService.getTitle(pa3);
                if(titlePa3 != null){
                    pa3.setTitle(titlePa3.getTitle());
                }
                pageAnalysisList.add(pa3);
            }

            // 插入一条?参数合并
            PageAnalysis pa2 = new PageAnalysis();
            pa2.setUrl(searchUrl + "?参数合并");
            pa2.setTitle("合并");
            pageAnalysisList.add(pa2);

        }else {
            // 不属于特殊url
            pageAnalysisList = pageAnalysisService.listChildren(pageAnalysis);
            // 把查询的url放在第一行
            if(pageAnalysisList.size() > 1){
                int index = 0;
                for (int i = 0; i < pageAnalysisList.size(); ++i) {
                    if (pageAnalysisList.get(i).getUrl().equals(pageAnalysis.getUrl())) {
                        index = i;
                        break;
                    }
                }
                Collections.swap(pageAnalysisList, 0, index);
            }
        }

        result.success(pageAnalysisList);
        return result;
    }

    /**
     * 总汇总
     *
     * @return
     */
    @RequestMapping(value = "sum")
    public AntdProResult sum(@RequestBody PageAnalysis pageAnalysis) {
        AntdProResult result = new AntdProResult();
        List<PageAnalysis> pageAnalysisList = pageAnalysisService.sum(pageAnalysis);
        result.setData(pageAnalysisList);
        return result;
    }

    /**
     * 按天汇总
     *
     * @return
     */
    @RequestMapping(value = "sumByDay")
    public AntdProResult sumByDay(@RequestBody PageAnalysis pageAnalysis) {
        AntdProResult result = new AntdProResult();
        List<PageAnalysis> pageAnalysisList = pageAnalysisService.sumByDay(pageAnalysis);
        result.setData(pageAnalysisList);
        return result;
    }

    /**
     * 按地市汇总
     *
     * @return
     */
    @RequestMapping(value = "sumByCity")
    public AntdProResult sumByCity(@RequestBody PageAnalysis pageAnalysis) {
        AntdProResult result = new AntdProResult();
        List<PageAnalysis> pageAnalysisList = pageAnalysisService.sumByCity(pageAnalysis);

        List<PageAnalysis> resultList = new ArrayList<>();
        PageAnalysis pa = new PageParamAnalysis();
        pa.setDate("合并");
        pa.setCityPvUvByList(pageAnalysisList);
        resultList.add(pa);

        result.setData(resultList);
        return result;
    }

    /**
     * 按地市和日期汇总
     *
     * @return
     */
    @RequestMapping(value = "sumByCityAndDay")
    public AntdProResult sumByCityAndDay(@RequestBody PageAnalysis pageAnalysis) {
        AntdProResult result = new AntdProResult();
        List<PageAnalysis> pageAnalysisList = pageAnalysisService.sumByCityAndDay(pageAnalysis);
        // 按日期分组
        Map<String, List<PageAnalysis>> pageAnalysisListMap = pageAnalysisList.stream().collect(Collectors.groupingBy(PageAnalysis::getDate));
        List<PageAnalysis> resultList = new ArrayList<>();
        for(String key : pageAnalysisListMap.keySet()){
            PageAnalysis pa = new PageAnalysis();
            pa.setDate(key);
            pa.setCityPvUvByList(pageAnalysisListMap.get(key));
            resultList.add(pa);
        }

        // 排序
        resultList = resultList.stream().sorted(Comparator.comparing(PageAnalysis::getDateNumber)).collect(Collectors.toList());

        result.setData(resultList);
        return result;
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "exportExcel")
    public AntdProResult exportExcel(@RequestBody PageAnalysis pageAnalysis, HttpServletResponse response) throws IOException {
        List<PageAnalysis> pageAnalysisList;
        if("1".equals(pageAnalysis.getIsMerge())){
            pageAnalysisList = pageAnalysisService.sum(pageAnalysis);
        }else {
            pageAnalysisList = pageAnalysisService.sumByDay(pageAnalysis);
        }
        // 组装数据
        Map<String, List<List<Object>>> map = new HashMap<>();
        List<List<Object>> data = new ArrayList<>();
        // 添加标题
        data.add(new ArrayList(){{add("日期");add("PV");add("UV");}});
        // 添加数据
        if (CollectionsUtils.isNotEmpty(pageAnalysisList)) {
            for (PageAnalysis pa : pageAnalysisList) {
                List<Object> resultDataList = new ArrayList<>();
                resultDataList.add(pa.getDate());
                resultDataList.add(pa.getPv().toString());
                resultDataList.add(pa.getUv().toString());
                data.add(resultDataList);
            }
        }
        map.put("Sheet1", data);
        ExcelUtils excelUtils = new ExcelUtils(1, map, true);
        Annex annex = excelUtils.writeAnnex("页面访问次数及访问用户（明细）" + pageAnalysis.getStartDate() + "-" + pageAnalysis.getEndDate() + ".xls");

        AntdProResult result = new AntdProResult();
        result.success(annex);
        return result;
    }

}
